package com.yx.frame.builder;

import java.util.List;

import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Button;
import org.eclipse.wb.swt.SWTResourceManager;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;

import com.yx.frame.builder.validate.ServiceBuilderConfigManager;
import com.yx.frame.builder.xml.MethodContentXml;
import com.yx.frame.builder.xml.MethodParmXml;
import com.yx.frame.builder.xml.MethodXml;
import com.yx.frame.builder.xml.QueryMethodContentXml;
import com.yx.frame.builder.xml.UpdateMethodContentXml;
import com.yx.frame.http.NioHttpClient;

import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.json.JSONArray;
import org.json.JSONObject;

public class MethodTest extends Dialog {

	protected Object result;
	protected Shell shell;
	private Text Url;
	private Text UserName;
	private Text Password;
	private Table Parms;
	private Text TestTime;
	private Text TotalTime;
	private Text Values;
	private ProgressBar progressBar;
	MethodXml methodXml;

	/**
	 * Create the dialog.
	 * 
	 * @param parent
	 * @param style
	 */
	public MethodTest(Shell parent, int style, MethodXml methodXml) {
		super(parent, style);
		setText("方法测试：" + methodXml.getName() + " - " + methodXml.getComment());
		this.methodXml = methodXml;
	}

	/**
	 * Open the dialog.
	 * 
	 * @return the result
	 */
	public Object open() {
		createContents();
		shell.open();
		shell.layout();
		Display display = getParent().getDisplay();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
		return result;
	}

	/**
	 * Create contents of the dialog.
	 */
	private void createContents() {
		shell = new Shell(getParent(), SWT.DIALOG_TRIM | SWT.PRIMARY_MODAL);
		shell.setSize(547, 448);
		shell.setText(getText());

		Label lblUrl = new Label(shell, SWT.NONE);
		lblUrl.setBounds(10, 10, 61, 17);
		lblUrl.setText("URL地址：");

		Url = new Text(shell, SWT.BORDER);
		Url.setEditable(false);
		Url.setText(ServiceBuilderConfigManager.getInstance().getServerUrl());
		Url.setBounds(71, 7, 178, 23);

		Label label = new Label(shell, SWT.NONE);
		label.setBounds(255, 10, 53, 17);
		label.setText("用户名：");

		UserName = new Text(shell, SWT.BORDER);
		UserName.setBounds(311, 7, 84, 23);

		Label label_1 = new Label(shell, SWT.NONE);
		label_1.setBounds(399, 10, 37, 17);
		label_1.setText("口令：");

		Password = new Text(shell, SWT.BORDER);
		Password.setBounds(438, 7, 84, 23);

		Parms = new Table(shell, SWT.BORDER | SWT.FULL_SELECTION);
		final TableEditor editor = new TableEditor(Parms);
		Parms.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				Control oldEditor = editor.getEditor();
				if (oldEditor != null)
					oldEditor.dispose();
				int idx = Parms.getSelectionIndex();
				TableItem item = Parms.getItem(idx);
				Text newEditor = new Text(Parms, SWT.NONE);
				newEditor.addModifyListener(new ModifyListener() {
					public void modifyText(ModifyEvent me) {
						Text text = (Text) editor.getEditor();
						editor.getItem().setText(2, text.getText());
					}
				});
				newEditor.selectAll();
				newEditor.setFocus();
				editor.setEditor(newEditor, item, 2);
			}
		});

		Parms.setBounds(10, 41, 515, 161);
		Parms.setHeaderVisible(true);
		Parms.setLinesVisible(true);
		TableColumn tc1 = new TableColumn(Parms, SWT.LEFT);
		TableColumn tc2 = new TableColumn(Parms, SWT.LEFT);
		TableColumn tc3 = new TableColumn(Parms, SWT.LEFT);
		tc1.setText("参数名称");
		tc2.setText("参数描述");
		tc3.setText("取值");
		tc1.setWidth(120);
		tc2.setWidth(120);
		tc3.setWidth(220);

		List<MethodParmXml> list = methodXml.getMethodParms();
		for (int i = 0; i < list.size(); i++) {
			MethodParmXml pXml = list.get(i);
			TableItem item = new TableItem(Parms, SWT.NONE);
			if ("true".equals(pXml.isMutilistType())) {
				item.setText(new String[] { pXml.getName(),
						pXml.getComment() + "(多条)", "" });
			} else {
				item.setText(new String[] { pXml.getName(), pXml.getComment(),
						"" });
			}
		}
		if ("query".equals(methodXml.getType())
				&& "true".equals(methodXml.getPagination())) {
			TableItem item = new TableItem(Parms, SWT.NONE);
			item.setText(new String[] { "PageIndex", "第几页", "0" });
			TableItem item1 = new TableItem(Parms, SWT.NONE);
			item1.setText(new String[] { "PageSize", "每页多少条", "50" });
		}
		MethodContentXml methodContentXml = methodXml.getMethodContentXml();
		if (methodContentXml instanceof UpdateMethodContentXml) {
			if ("true".equals(((UpdateMethodContentXml) methodContentXml)
					.getUserDefineDatasource())) {
				TableItem item = new TableItem(Parms, SWT.NONE);
				item.setText(new String[] {
						"DatasourceOf" + methodXml.getName(), "数据源(单个)", "" });
			}
		} else if (methodContentXml instanceof QueryMethodContentXml) {
			QueryMethodContentXml queryMethodContentXml = (QueryMethodContentXml) methodContentXml;
			List<String> queryUserDefineDatasource = queryMethodContentXml
					.getUserDefineDatasource();
			for (int i = 0; i < queryUserDefineDatasource.size(); i++) {
				TableItem item = new TableItem(Parms, SWT.NONE);
				item.setText(new String[] { queryUserDefineDatasource.get(i),
						"数据源(多个)", "" });
			}
		}
		progressBar = new ProgressBar(shell, SWT.NONE);
		progressBar.setBounds(10, 213, 299, 17);

		Button btnNewButton = new Button(shell, SWT.NONE);
		btnNewButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				Display.getDefault().syncExec(new Runnable() {
					public void run() {
						try {
							Values.setText("");
							progressBar.setMinimum(0);
							progressBar.setSelection(0);
							TotalTime.setText("0");
							JSONObject jRequest = new JSONObject();
							List<MethodParmXml> list = methodXml
									.getMethodParms();
							for (int i = 0; i < list.size(); i++) {
								MethodParmXml pXml = list.get(i);
								TableItem item = Parms.getItem(i);
								String pName = pXml.getName();
								String pValue = item.getText(2);
								if (pXml.isMutilistType()) {
									JSONArray array = new JSONArray();
									String[] valueList = pValue.split(",");
									for (int j = 0; j < valueList.length; j++) {
										array.put(valueList[j]);
									}
									try {
										jRequest.put(pName, array);
									} catch (Exception ex) {
										addMessage("初始化错误:" + ex);
										return;
									}
								} else {
									try {
										jRequest.put(pName, pValue);
									} catch (Exception ex) {
										addMessage("初始化错误:" + ex);
										return;
									}
								}
							}
							int pointer=list.size();
							if ("query".equals(methodXml.getType())
									&& "true".equals(methodXml.getPagination())) {
								pointer=pointer+2;
								for (int i = list.size(); i < pointer; i++) {
									TableItem item = Parms.getItem(i);
									String pName = item.getText(0);
									String pValue = item.getText(2);
									try {
										jRequest.put(pName, pValue);
									} catch (Exception ex) {
										addMessage("初始化错误:" + ex);
										return;
									}
								}
							}
							MethodContentXml methodContentXml = methodXml
									.getMethodContentXml();
							if (methodContentXml instanceof UpdateMethodContentXml) {
								if ("true"
										.equals(((UpdateMethodContentXml) methodContentXml)
												.getUserDefineDatasource())) {
									TableItem item = Parms.getItem(pointer);
									String pName = item.getText(0);
									String pValue = item.getText(2);
									try {
										jRequest.put(pName, pValue);
									} catch (Exception ex) {
										addMessage("初始化错误:" + ex);
										return;
									}
								}
							} else if (methodContentXml instanceof QueryMethodContentXml) {
								for (int i = pointer; i < Parms
										.getItemCount(); i++) {
									TableItem item = Parms.getItem(i);
									String pName = item.getText(0);
									String pValue = item.getText(2);
									JSONArray array = new JSONArray();
									String[] valueList = pValue.split(",");
									for (int j = 0; j < valueList.length; j++) {
										array.put(valueList[j]);
									}
									try {
										jRequest.put(pName, array);
									} catch (Exception ex) {
										addMessage("初始化错误:" + ex);
										return;
									}
								}
							}
							NioHttpClient.setServerUrl(Url.getText().trim());
							NioHttpClient.setUser(UserName.getText()
									.trim(), Password.getText().trim());
							int runTime = 0;
							try {
								runTime = Integer.parseInt(TestTime.getText()
										.trim());
							} catch (Exception ex) {
								addMessage("初始化错误:" + ex);
							}
							if (runTime < 1) {
								addMessage("执行次数必须填写大于零的数字！");
								return;
							}
							int actionId = methodXml.getId();
							progressBar.setMaximum(runTime);
							long t = System.currentTimeMillis();
							JSONObject ret = null;
							boolean isAsync=false;
							if("true".equals(methodXml.getAsyncService())){
								isAsync=true;
							}
							for (int i = 0; i < runTime; i++) {
								try {
									ret = NioHttpClient.post(actionId,isAsync, jRequest);
								} catch (Exception ex) {
									addMessage("第" + (i + 1) + "执行出错误:" + ex);
								}
								progressBar.setSelection((i + 1));
							}
							if (ret != null) {
								addMessage(ret.toString());
							}
							TotalTime.setText(""
									+ (System.currentTimeMillis() - t));
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
			}
		});
		btnNewButton.setBounds(311, 208, 53, 27);
		btnNewButton.setText("测试");

		TestTime = new Text(shell, SWT.BORDER | SWT.RIGHT);
		TestTime.setText("1");
		TestTime.setBounds(367, 210, 44, 23);

		Label label_2 = new Label(shell, SWT.NONE);
		label_2.setBounds(413, 213, 19, 17);
		label_2.setText("次");

		TotalTime = new Text(shell, SWT.BORDER | SWT.RIGHT);
		TotalTime.setForeground(SWTResourceManager.getColor(SWT.COLOR_RED));
		TotalTime.setEditable(false);
		TotalTime.setBounds(438, 210, 53, 23);

		Label label_3 = new Label(shell, SWT.NONE);
		label_3.setText("毫秒");
		label_3.setBounds(497, 213, 25, 17);

		Values = new Text(shell, SWT.BORDER | SWT.WRAP | SWT.V_SCROLL
				| SWT.MULTI);
		Values.setForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_GREEN));
		Values.setBounds(10, 238, 515, 172);

	}

	public void addMessage(String msg) {
		Values.append(msg + "\r\n");
	}
}
